#!/bin/bash


###############################################################################
#                                                                             #
# BVC: a kdialog script for converting and combining seperate clips into one  #
# svcd or dvd format video stream,  with title, lead-in and fades,            #
#  and burning them to disk.                                                  #
#                                                                             #
# It uses ffmpeg, png2yuv (mjpegtools), mplayer/mencoder, growisofs, cdrdao,  #
# imagemagick, sox, vcdimager, and dvdauthor (k3b is optional).               #
# kmplayer is suggested for nice previews of videos in the file dialog.       #
# (kmplayer.sourceforge.net)                                                  #
#                                                                             #
# (If you are just doing DVD's you don't need vcdimager or cdrdao             #
# and if just doing SVCD's you don't need dvdauthor or growisofs.)            #
#                                                                             #
# It was originally written for short clips from a  camera, but it could      #
# be used for any similar purpose                                             #
#                                                                             #
# by Robert Sohn <grepper@gmail.com> (grepper on irc.freenode.net)            #
#                                                                             # 
###############################################################################

TARGET="DVD"
DVD_DEVICE="/dev/dvd"
CDROM_DEVICE="/dev/cdrom"
WIN_TITLE="BVC"
#FRAME_STYLE="none"
TOTAL_PNGS=230
WORK_DIR="$HOME/tmp/BVC"
BVC_LOG=$WORK_DIR/BVC.log
DATA_DIR="/usr/share/BVC/data"
KDIALOG="kdialog"
KDIALOG_OPTS="--icon mplayer --miniicon mplayer"
LINE=$(for ((i=1; i<=79; i++));do echo -n =;done)
OUTPUT="the output"
SORRY_MSG="<html><h4>Oops...<p>Something went wrong, $OUTPUT was not created. \
Please check the log at $BVC_LOG"
DVDRW_MEDIA="PLUS_R"
VCD_XML="$WORK_DIR/mydisc.xml"
FADE=0.5  # number of seconds to fade the audio in and out in each clip
DO_FADE=true
FRAME_CMD="fancy"
FONT_STYLE=""  #  FIX not used yet
ARGS="$@"
VFRAMES=""
ANIMATE="false"
ANI_LENGTH=""
INTRO_VIDEO="$WORK_DIR/intro.avi"


###############################################################################
#                               FUNCTIONS                                     #
###############################################################################


function usage()
{
echo -e "Usage: `basename $0` -S (SVCD)|-D (DVD)
        Other options: \n \
        -n <no audio fade in/out> Default: fade 1.0 seconds \n \
        -f <fade audio in/out in secs.   eg. 1.0 or 0.5>. Default: -f 1 \n \
        -b <frame border style> fancy, steel, round, or none. Default: fancy \n \
        -d <cdrom or dvd device> Default: /dev/cdrom and /dev/dvd respectively\n"
        
}

function usage2()
{
    echo -e "\nError: option requires an argument.\n \
    For -b use either 'fancy', 'steel', 'round', or 'none'. \n \
    For -f give fade-in/fade-out time in seconds, ie. 1.0 or 0.6\n \
    For -d give device name: Default /dev/dvd for DVD or /dev/cdrom for SVCD\n"

}

function fancy()
# thanks to Anthony Thyssen http://www.cit.gu.edu.au/~anthony/graphics/imagick6
# for this function: the pngs used are copies of his example gifs
# usage: fancy infile <infile dimension (XxY)> <outfile>
{

DIM=`identify -format %wx%h $1`
NEW_DIM=$2
for i in $1; do
    convert -size $DIM $1 \
    -thumbnail "$NEW_DIM>" \
    -matte  -compose Copy \
    -bordercolor Black -border 2 -bordercolor Sienna4 -border 3 \
    -bordercolor Black -border 1 -bordercolor none -border 2 \
    -bordercolor Black -border 2 -bordercolor Sienna4 -border 3 \
    -bordercolor Black -border 1 \
    -compose Over \
    \( $DATA_DIR/fancy_add.png \) -gravity NorthWest -composite \
    \( $DATA_DIR/fancy_add.png -flip       \) -gravity SouthWest -composite \
    \( $DATA_DIR/fancy_add.png       -flop \) -gravity NorthEast -composite \
    \( $DATA_DIR/fancy_add.png -flip -flop \) -gravity SouthEast -composite \
    -compose DstOut \
    \( $DATA_DIR/fancy_sub.png \)             -gravity NorthWest -composite \
    \( $DATA_DIR/fancy_sub.png -flip       \) -gravity SouthWest -composite \
    \( $DATA_DIR/fancy_sub.png       -flop \) -gravity NorthEast -composite \
    \( $DATA_DIR/fancy_sub.png -flip -flop \) -gravity SouthEast -composite \
    $3
done

}

# the rounding function below borrowed from someone called Astarna,
# kind enough to post his solution to a problem on the magic-users mailing list
# http://studio.imagemagick.org/pipermail/magick-users/2004-September/013557.html

function round()
{
IMG="$1"
OUTFILE="$3"
DIM2="$2"
DIM=`identify -format %wx%h $IMG`
# create the mask for the image
# 10,10 is the position... 0,0 would be centered
# 220,200 is the size of the circle
convert -size $DIM xc:black \
        -fill white \
        -draw "RoundRectangle 10,10 220,220, 105,105" \
        +matte \
        -compose CopyOpacity \
        mask.png

# create the shadow
# need to change the position, and expand it.
# #999999 is the shade... and set the gaussian 7x7
convert -size $DIM xc:white \
        -fill "#999999" \
        -draw "RoundRectangle 20,20 235,235, 105,105" \
        -blur 7x7 \
        -fill white \
        -matte \
        mask_shadow.png

# implement the mask.. once mask is created underlay the shadow
composite -compose CopyOpacity \
        mask.png -background white $IMG $OUTFILE
# add the shadow
convert $OUTFILE -background none  \
        mask_shadow.png \
        -compose Dst_Over tmp.png
if [ $TARGET = "DVD" ]; then
    convert $OUTFILE -gravity East   -chop 30%x0 -resize 115%! $OUTFILE
elif [ $TARGET = "SDVD" ]; then
    convert $OUTFILE -gravity East -chop 35%x0 \
#-gravity South -chop 30%x0 $OUTFILE
    convert $OUTFILE -gravity South -chop 30%x0 -resize 150%! $OUTFILE
fi
#convert  $OUTFILE -trim +repage $OUTFILE
#convert -resize $2! $OUTFILE $OUTFILE
cp $OUTFILE ~/tmp/
}


function steel()
# this creates a steel frame instead of a fancy frame
{
convert -size $2 -border 4x4 -bordercolor "#444744" -raise 2x2 "$1" "$3"
}


function progress_bar_progress()
# increment the progress bar
{
inc=$((`dcop $dcopRef progress` + $1))
dcop $dcopRef setProgress $inc
}

function shadow()
# takes one parameter, the pics/? dir
{

convert -page +6+6 $1 \
\( +clone -background navy -shadow 60x8+6+6 \) +swap \
-background none  -flatten -shave 11x11  +repage \
$1
convert -gravity East -chop 30x0 $1 $1
convert -gravity South  -chop 0x30 $1 $1

}


set_progress_bar_label()
# for just setting label with no increment
{
dcop `dcop |grep kdialog` ProgressDialog setLabel "$PROGRESS_LABEL"
}

function cleanlog()
# process $BVC_LOG.tmp variously - eg. ffmpeg's output is ugly without this
{
FOLD="fold -bs"
NO_CR="tr -d '\r'"
RELINE="{s/$SED_VAR/\n$SED_VAR/g}"
TMP_LOG="$BVC_LOG.tmp"
NOSPACE="tr -s ' '"


case "$1" in
    1 )
        $FOLD $TMP_LOG >> $BVC_LOG
        echo >> $BVC_LOG
        ;;
    2 )
        $NO_CR < $TMP_LOG | $FOLD >> $BVC_LOG
        echo >> $BVC_LOG
        ;;
    3 ) 
        $NO_CR < $TMP_LOG | sed $RELINE | $FOLD >> $BVC_LOG
        echo >> $BVC_LOG
        ;;
    4 )
        $NOSPACE < $TMP_LOG | $FOLD >> $BVC_LOG
        ;; 
esac

rm -f $BVC_LOG.tmp
}

function vid_length()
{
mencoder "$1" -quiet \
-ovc copy -oac pcm -o /dev/null |grep "Video stream"|awk '{print $10}'
}

function frame_rate() 
{
FRAME_RATE=$(mencoder $1 -oac pcm -ovc copy -o /dev/null |grep VIDEO:|
awk '{print $5}')
}

function sorry_msg()
{
echo "<html><h4>Oops . . .<p>Something went wrong, there was a problem \
creating the $OUTPUT.<br> \
Please check the log at $BVC_LOG</html>"
}

function centre() ## USAGE: centre width text...
{
   c_width=$1
   shift
   c_text="$*"
   c_width=$(( ($c_width + ${#c_text}) / 2 ))
   printf "%${c_width}.${c_width}s\n" "$c_text"
}

function cleanup()
{
dcop `dcop |grep kdialog` ProgressDialog >/dev/null 2>&1
if [ $? -eq 0 ]; then
    dcop $dcopRef close;exit
else
    exit 1
fi
}

function static_fade()
# this is suitable for fades for static images, not animated sequences
# usage: static_fade type <string discribing fade type for progress bar
{
# check args
if [[ -n $2 && $2 = "-fo" ]]; then
:
else
# use -dissolve to create fade effect
    S=100
    for ((X=0; X<50; X++)) ; do
        PROGRESS_LABEL="processing $X.png of $1"
        set_progress_bar_label
        composite -dissolve $S $WORK_DIR/black.png \
        "${FADIN_PNGS[X]}" "${FADIN_PNGS[X]}"
        S=$((S-2))
    done
# update progress bar
#progress_bar_progress  $PROG_INC
PROGRESS_LABEL="Finished $1 fade-ins"
set_progress_bar_label
sleep 1
fi

# do fade-outs
S=0
for ((Y=0; Y<50; Y++)) ; do
    PROGRESS_LABEL="processing $Y.png of $1"
    set_progress_bar_label
    composite -dissolve $S $WORK_DIR/black.png \
    "${FADEOUT_PNGS[Y]}" "${FADEOUT_PNGS[Y]}"
    S=$((S+2))
done

}


###############################################################################
#                       END OF FUNCTIONS                                      #
###############################################################################


###############################################################################
#            allow for either dvd or svcd conversion/burning                  #
###############################################################################

SVCD_VID_SIZE_OPT="480x480"
DVD_VID_SIZE_OPT="720x480"
DVD_AUDIO_EXT=ac3
SVCD_AUDIO_EXT=mp2
DVD_SAMPLERATE="48000"
SVCD_SAMPLERATE="44100"
DVD_AUDIO_OPTS="-ab 224 -ar 48000 -ac 2 -acodec $DVD_AUDIO_EXT"
SVCD_AUDIO_OPTS="-ab 224 -ar 44100 -ac 2 -acodec $SVCD_AUDIO_EXT"
SVCD_FFMPEG_TARGET="ntsc-svcd"
DVD_FFMPEG_TARGET="ntsc-dvd"
SVCD_FFMPEG_OPTS="-b 2080 -maxrate 2080 -bufsize 230 -aspect 4:3"
DVD_FFMPEG_OPTS="-b 8000  -maxrate 9000 -bufsize 230  -aspect 4:3"
SVCD_INTRO_SIZE="240x240"
DVD_INTRO_SIZE="360x240"
SVCD_MPLEX_FORMAT=4
DVD_MPLEX_FORMAT=8
SVCD_TITLE_FONT_SIZE=32
DVD_TITLE_FONT_SIZE=36
DVD_GEO_ARRAY=(360x240 270x180 192x128 192x128 180x120 180x120 144x96 144x96 \
144x96 144x96 144x96 144x96 96x64 96x64 96x64 96x64 96x64 96x64 96x64 96x64 \
72x48 72x48 72x48 72x48 72x48 72x48 72x48 72x48 72x48 72x48)
SVCD_GEO_ARRAY=(240x240 180x180 120x120 120x120 120x120 120x120 96x96 96x96 \
96x96 96x96 96x96 96x96 96x96 64x64 64x64 64x64 64x64 64x64 64x64 64x64 \
48x48 48x48 48x48 48x48 48x48 48x48 48x48 48x48 48x48 48x48)
TILE_ARRAY=(1x1 2x1 2x2 2x2 3x2 3x2 3x3 3x3 3x3 4x3 4x3 4x3 4x4 4x4 4x4 \
4x4 5x4 5x4 5x4 5x4 5x5 5x5 5x5 5x5 5x5 6x5 6x5 6x5 6x5 6x5)


# test if BVC is installed or running from current dir
if [ -d $DATA_DIR ]; then
    DATA_DIR=$DATA_DIR
else
    DATA_DIR=`pwd`/data
fi

# check if user called with proper arg, and exit if not (getopts sucks :P)

if [[ "$@" == *-S* || "$@" == *-D* ]]; then
    if [[ "$@" == *-S*-D* || "$@" == *-D*-S* || "$@" == *-SD* || \
    "$@" == *-DS* ]]; then
        echo -e "\nError: you must use one of: -D (DVD) OR -S (SVCD)\n"
        usage
        exit 1
    else
        :
    fi
else
    echo -e "\nError: you must specify either "-S" (SVCD) OR "-D" (DVD)\n"
    usage
    exit 1
fi
# in case user does something like ending with -b, -f, -t or -d with no arg
if echo  "$@"|egrep --  '-b$|-f$|-d$i|-t$' > /dev/null 2>&1; then
    usage2
    usage
    exit 1
fi
# -D (DVD) or -S (SVCD) lets a desktop file call either BVC-dvd or BVC-svcd
# see if what options the script is called with, and react accordingly 
while getopts ":SDt:b:nf:" Option
do
    case $Option in
    S )
        TARGET="SVCD"
        VID_SIZE_OPT=$SVCD_VID_SIZE_OPT
        AUDIO_OPTS=$SVCD_AUDIO_OPTS
        SAMPLERATE=$SVCD_SAMPLERATE
        AUDIO_EXT=$SVCD_AUDIO_EXT
        FFMPEG_TARGET=$SVCD_FFMPEG_TARGET
        INTRO_SIZE=$SVCD_INTRO_SIZE
        FFMPEG_OPTS=$SVCD_FFMPEG_OPTS
        MPLEX_FORMAT=$SVCD_MPLEX_FORMAT
        TITLE_FONT_SIZE=$SVCD_TITLE_FONT_SIZE
        GEO_ARRAY=("${SVCD_GEO_ARRAY[@]}")
        ;;
    D )
        TARGET="DVD"
        VID_SIZE_OPT=$DVD_VID_SIZE_OPT
        AUDIO_OPTS=$DVD_AUDIO_OPTS
        SAMPLERATE=$DVD_SAMPLERATE
        AUDIO_EXT=$DVD_AUDIO_EXT
        FFMPEG_TARGET=$DVD_FFMPEG_TARGET
        INTRO_SIZE=$DVD_INTRO_SIZE
        FFMPEG_OPTS=$DVD_FFMPEG_OPTS
        MPLEX_FORMAT=$DVD_MPLEX_FORMAT
        TITLE_FONT_SIZE=$DVD_TITLE_FONT_SIZE
        GEO_ARRAY=("${DVD_GEO_ARRAY[@]}")
        ;;
    n )
        DO_FADE="false"
        ;;
    f ) 
        if [ -z "$OPTARG" -o "${OPTARG:0:1}" = "-" ] ;then
        usage2
        usage
        exit 1
        fi
        FADE="$OPTARG"
        ;;
    b ) 
        if [ -z "$OPTARG" -o "${OPTARG:0:1}" = "-" ] ;then

             usage2
             usage
             exit 1
        fi
        FRAME_STYLE="$OPTARG"
        if [ $FRAME_STYLE = "fancy" ]; then
            FRAME_FONT="$DATA_DIR/Candice.ttf"
            FRAME_CMD="fancy"
        elif [ $FRAME_STYLE = "steel" ]; then
            FRAME_CMD="steel"
        elif [ $FRAME_STYLE = "round" ]; then
            FRAME_CMD="round"
        elif [ $FRAME_STYLE = "none" ]; then
            :
        else  
            usage2
            usage
            exit 1
        fi
        ;;
    d )
        DEVICE="$OPTARG"
        ;;
    t )
         if [ -z "$OPTARG" -o "${OPTARG:0:1}" = "-" ] ;then
             usage2
             usage
             exit 1
        fi
        TITLE_PAGE="$OPTARG"
        ;;
    esac
done
shift $(($OPTIND - 1))

# create a default if user doesn't specify DEVICE or if called from BVC*.desktop
if [ ! "$DEVICE" ]; then
    if [ "$TARGET" = "DVD" ]; then
        if [ -b /dev/dvdrw ]; then 
            DEVICE=/dev/dvdrw
        elif [ -b /dev/dvd ]; then 
            DEVICE=/dev/dvdrw
        else
            $KDIALOG $KDIALOG_OPTS --sorry \
            "<html><h4>Sorry, no dvdrw device found<p> \
            Please symlink your device to /dev/dvdrw or /dev/dvd</html>"
            exit 1
         fi
    elif [ "$TARGET" = "SVCD" ]; then
        if [ -b /dev/cdrw ]; then 
            DEVICE=/dev/cdrw
        elif [ -b /dev/cdrom ]; then 
            DEVICE=/dev/cdrom
            $KDIALOG $KDIALOG_OPTS --yesno "<html><h4>The device symlink \
            /dev/cdrw was not found.<p>We are going to try using /dev/cdrom. \
            <p>If this is incorrect, quit now and symlink your device to \
            /dev/cdrw.<p>Do you want to continue ?</html>"
                if [ $? = 1 ]; then
                    exit 1
                fi
        else
            $KDIALOG $KDIALOG_OPTS --sorry \
            "<html><h4>Sorry, no CD burning device found<p> \
            Please symlink your device to /dev/cdrw or /dev/cdrom</html>"
            exit 1
         fi
    fi
fi
# check dvdrw-rw or dvdrw+rw status
# maybe I'll even use this someday
if [ $DVDRW_MEDIA = PLUS_R ];then
    BLANK="-leadin"
elif [ $DVDRW_MEDIA = MINUS_R ]; then
    BLANK="-blank"
fi

###############################################################################
#           BEGIN: kdialog greeting, and see if user wants to continue        #
###############################################################################

GREETING="<html><h3><u>BEN'S VIDEO CONVERTER</u></h3><p><h4>A program to convert \
camera movie files into a format that can be used on a $TARGET disk. \
<p>When the file browser comes up next, choose the files that you \
want to combine into one video.<br>Choose them one at a time. in the order \
you want them arranged on the video, and press 'Open' for each one. \
<br><br>You can preview them if you make sure 'Show preview' is selected \
when you click on the icon shaped like a wrench at the top of the file \
browser that comes up.<h5> \
* install kmplayer if this doesn't work for you *<br></h5>
<h4><font color='#0000C6' weight=900>When you are done selecting your video \
clips, press the 'Cancel' button the next time the file browser comes up \
and the processing will start.</font><br> \
<br>To begin press 'Yes' , to exit  press 'No'.</H4> \
<p><H3>Do you want to continue ?</html>"

$KDIALOG $KDIALOG_OPTS $WIN_TITLE --yesno  "$GREETING"
if [ $? != 0 ]; then
    exit 0
fi


###############################################################################
#        set up WORK_DIR and create videocd.xml or dvdauthor.xml as needed    #
###############################################################################


# create a user's tmp dir if it doesn't exist
# if it exists, move it to a new name
if [ -d $WORK_DIR ]; then
    mv $WORK_DIR $WORK_DIR-`date "+%s"`
    mkdir -p $WORK_DIR
    else
    mkdir -p  $WORK_DIR
fi



# create basic dvdauthor.xml
if [ $TARGET = "DVD" ]; then
    DVD_AUTHOR_XML="$WORK_DIR/dvdauthor.xml"
    (
    cat <<EOF 
    <dvdauthor dest="$WORK_DIR/FINAL">
    <vmgm>
    </vmgm>
    <titleset>
      <titles>
        <pgc>
          <vob file="$WORK_DIR/final.mpg" chapters="0" />
        </pgc>
      </titles>
    </titleset>
    </dvdauthor>
EOF
    ) | sed 's/^    //' > "$DVD_AUTHOR_XML"

fi

##############################################################################
#   get the file names, start progress bar, and create WORK_DIR directories  # 
##############################################################################

# do processing in $WORK_DIR
cd $WORK_DIR

v=0
t=0
while [ $? = 0 ]; do
    VID_ARRAY[$v]=$($KDIALOG $KDIALOG_OPTS --separate-output \
    --getopenfilename :label2 "*.avi *.AVI *.mov *.MOV *.mpg *.MPG \
    *.mpeg *.MPEG *.m2v *.M2V|videos") 2>/dev/null
        if [ $? = 0 ]; then
            v=$((v+1))
            TITLES_ARRAY[$t]="$($KDIALOG $KDIALOG_OPTS --inputbox \
            "What name would you like to use for your clip?" \
            "The Big Serve")" >/dev/null 2>&1
            t=$((t+1))
        else
            unset VID_ARRAY[$v]
            break
        fi
done

V_ARRAY_TOTAL=${#VID_ARRAY[@]}
A_ARRAY_TOTAL=${#TITLES_ARRAY[@]}
FILES=$(($V_ARRAY_TOTAL - 1))

# make sure the user didn't press cancel before doing anything
# even if user cancels out of title dialog, array total should still be >= 2
echo -e "V_ARRAY_TOTAL is $V_ARRAY_TOTAL"
echo -e "FILES are $FILES"
VA_ARRAY_TOTAL=$(($V_ARRAY_TOTAL + $A_ARRAY_TOTAL))
if [ $VA_ARRAY_TOTAL -lt 2 ];then
    exit 0
fi
echo -e "ARGS are $ARGS"
#if [[ "$ARGS" == *b* ]] || [ egrep FRAME.*'fancy|steel|round|none'  ~/.bvc >/dev/null 2>&1 ]; then
#if echo  "$@"|egrep 'fancy|steel|round|none' || [ egrep FRAME.*'fancy|steel|round|none'  ~/.bvc ]; then
echo  "$ARGS"|egrep 'fancy|steel|round|none' >/dev/null 2>&1
if [ "$?" = "0" ]; then
    :
else
    IN_FRAME_STYLE=$(kdialog --radiolist "<html>Please select the type of frame style you want to use \
    <br><align left>This will frame the clip title intros that will be created</html> \
    " 1 "fancy frame" on 2 "steel frame" off 3 "round frame with shadow" off 4 "no frame" off)
    case "$IN_FRAME_STYLE" in
        1 )
            FRAME_STYLE="fancy"
            ;;
        2 )
            FRAME_STYLE="steel"
            FRAME_CMD="steel"
            ;;
        3 )
            FRAME_STYLE="round"
            FRAME_CMD="round"
            ;;
        4 )
            FRAME_STYLE="none"
            ;;
    esac

fi

if [ $TITLE_PAGE ]; then
    :
else
    TITLE_PG=$(kdialog --radiolist "<html>Please select the type of introduction you would like \
    <br> to use for the main title page for your presentation </html>" \
    1 "Plain Style" on 2 "Animated" off 3 "None" off)
fi
    case "$TITLE_PG" in
        1 )
            TITLE_PAGE="plain"
            ;;
        2 )
            TITLE_PAGE="animated"
            ;;
        3 )
            TITLE_PAGE="none"
            ;;
    esac


# set up our log file
PATTERN=$(for ((i=1; i<=79; i++));do echo -n \*;done) 
printf "%s\n%s\n%s\n\n\n" "$PATTERN" \
"Ben's video Converter (BVC) - log for `date`" \
"$PATTERN" >> $BVC_LOG


dcopRef=$(kstart --ontop --window "Ben's Video Converter"  \
kdialog -geometry 400x100+0+0   --icon mplayer --miniicon mplayer \
--caption "Ben's Video Converter" --progressbar "$PROGRESS_LABEL")

# trap exits and errors so we can close kdialog
trap cleanup 0 2 15

# create_dirs
for ((i=0; i<=$FILES; i++)) ; do
    mkdir -p  $WORK_DIR/pics/$i/video_fadeout
done

if [ $TITLE_PAGE = "animated" ]; then
    mkdir $WORK_DIR/{animenu,montages,fade}
elif [ $TITLE_PAGE = "plain" ]; then
    mkdir $WORK_DIR/fade
fi

# create black png for dissolve
convert  -size $VID_SIZE_OPT xc:black $WORK_DIR/black.png


###############################################################################
#                       process original video and audio                      #
###############################################################################
# update progress bar
progress_bar_progress 1
PROGRESS_LABEL="converting source video to high bitrate mpeg-4"
set_progress_bar_label

# create high bitrate xvid avi's of our video clips
echo -e "VID_ARRAY is ${VID_ARRAY[@]}"
for ((i=0; i<=$FILES; i++)) ; do

    CURRENT_CLIP=${VID_ARRAY[$i]}
    FFMPEG_ENC_CMD=(ffmpeg -i "$CURRENT_CLIP"  -f avi -an -vcodec mpeg4 -b 3000 \
    -r 29.970 -s $VID_SIZE_OPT -aspect 4:3 $WORK_DIR/pics/$i/$i.avi)
    printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
    echo -e "\nRunning: ${FFMPEG_ENC_CMD[@]}" |fold -bs |tr -s ' ' >> $BVC_LOG

    SED_VAR="frame="
    if "${FFMPEG_ENC_CMD[@]}" >> $BVC_LOG.tmp 2>&1; then
        cleanlog 3
    else
        cleanlog 3
        OUTPUT="clips from your videos"
        SORRY_MSG=$(sorry_msg)
        $KDIALOG $KDIALOG_OPTS --sorry "$SORRY_MSG"
        dcop $dcopRef close
        exit 1
    fi

done

# put clips into an array, find out the shortest clip length
for ((i=0; i<=$FILES; i++)) ; do
    VID=( ${VID[@]} $(find $WORK_DIR/pics -name $i.avi) )
    VID_LENGTH=( ${VID_LENGTH[@]} $(vid_length ${VID[$i]}) )
    NEW_LENGTH=( ${NEW_LENGTH[@]}   ${VID_LENGTH[i]%.*} )
done

for val in ${NEW_LENGTH[@]}; do
    [ -z "$MIN_VAL" ] || ((val < MIN_VAL)) && MIN_VAL=$val
done

ANI_LENGTH=$(($MIN_VAL * 30))
if [ $ANI_LENGTH -gt 900 ]; then
    ANI_LENGTH=900
fi

VFRAMES=$ANI_LENGTH
echo -e "MIN_VAL is $MIN_VAL"
echo -e "ANI_LENGTH is $ANI_LENGTH"
sleep 5

# update progress bar
progress_bar_progress 10
PROGRESS_LABEL="Extracting audio and processing"
set_progress_bar_label

# extract audio from files, or if none, create silence
for ((i=0; i<=$FILES; i++)) ; do
    CURRENT_CLIP=${VID_ARRAY[$i]}
    if ! mplayer -identify -frames 0 -vo null -ao null "$CURRENT_CLIP" |
    grep "no sound"; then
        ffmpeg -i "$CURRENT_CLIP" -ar 44100 -ac 2 -acodec pcm_s16le -y \
        $WORK_DIR/pics/$i/$i.wav
    else
        TIME=${VID_LENGTH[$i]}
        cat /dev/zero | nice -n 0 sox -t raw -c 2 -r 48000 -w \
        -s - $WORK_DIR/pics/$i/$i.wav  trim 0 $TIME
    fi
done

# update progress bar
progress_bar_progress 3

#create fade effect on the extracted wavs
if [ $DO_FADE = "false" ]; then
    FADE=0
elif [ -z $FADE ]; then
    FADE=1
else
    FADE=$FADE
fi




for ((i=0; i<=$FILES; i++)) ; do
    WAV_TIME=${VID_LENGTH[$i]}

    echo -e "Running sox $WORK_DIR/pics/$i/$i.wav \
    $WORK_DIR/pics/$i/$i-processed.wav fade t $FADE $WAV_TIME $FADE"

    sox $WORK_DIR/pics/$i/$i.wav \
    $WORK_DIR/pics/$i/$i-processed.wav fade t $FADE $WAV_TIME $FADE
done

# convert faded wav to ac3 or mp2
for ((i=0; i<=$FILES; i++)) ; do
    ffmpeg -i $WORK_DIR/pics/$i/$i.wav \
$AUDIO_OPTS -y $WORK_DIR/pics/$i/$i.$AUDIO_EXT
done

# update progress bar
progress_bar_progress 3
PROGRESS_LABEL="Creating a Title lead-in for each clip"
set_progress_bar_label

###############################################################################
#             end of processing original video and audio                      #
###############################################################################

###############################################################################
#                       work on the clip title images                         #
###############################################################################


progress_bar_progress 1
PROGRESS_LABEL="Creating image files from the videos" 
set_progress_bar_label

# create the pngs for background image and move to proper pics/ dir
for ((i=0; i<=$FILES; i++)) ; do
    CREATE_PNG_CMD=(ffmpeg -i "${VID[$i]}" -vframes $VFRAMES -s "$INTRO_SIZE" \
    "$WORK_DIR/pics/$i/%d.png")
    printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
    echo -e "\nRunning: ${CREATE_PNG_CMD[@]}\n" | fold -bs >> $BVC_LOG

    SED_VAR="frame="
    if "${CREATE_PNG_CMD[@]}" >> $BVC_LOG.tmp 2>&1;then
        cleanlog 3
    else
        cleanlog 3
        OUTPUT="There was a problem creating pngs from the video. \
        Please see the output of $BVC_LOG"
        SORRY_MSG=$OUTPUT
        $KDIALOG --msgbox "$OUTPUT"
        dcop $dcopRef close
        exit 1
    fi

    convert -resize $INTRO_SIZE! $WORK_DIR/pics/$i/59.png \
    $WORK_DIR/pics/$i/intro.png

# clean up
# rm -f $WORK_DIR/pics/$i/000*.png 

done

progress_bar_progress 3
PROGRESS_LABEL="Making background and clip titles"
set_progress_bar_label
 
# create a title png with picture, frame and title

#  create black background
BG_PIC="$WORK_DIR/pics/template.png"
convert  -size $VID_SIZE_OPT xc:"#1E1E1E" $BG_PIC

FRAME_FONT="$DATA_DIR/Candice.ttf"
# font to use for our plain title text - fall back on Candice if no helvetica

if [ $FRAME_STYLE != "fancy" ] &&  [ $FRAME_STYLE != "round" ]; then
    if convert -font Helvetica -draw "text 0,0 'test'" $BG_PIC /dev/null; then
        FRAME_FONT="Helvetica"
    elif
        convert -font helvetica -draw "text 0,0 'test'" $BG_PIC /dev/null; then
            FRAME_FONT="helvetica"
    else
        FRAME_FONT=$FRAME_FONT
    fi
fi

for ((f=0; f<=$FILES; f++)) ; do
    if [ $FRAME_STYLE = "round" ]; then
        GRADIENT="dark_blue_gradient.png"
    else
        GRADIENT="aqua_gradient.png"
    fi

    #  create a transparant png with the title on it
    TITLE="\"${TITLES_ARRAY[$f]}\""
    convert -font $FRAME_FONT -pointsize $TITLE_FONT_SIZE -size 420x \
    -gravity Center caption:"$TITLE"  -negate  \( +clone -blur 0x8 \
    -shade 110x45 -normalize \
    $DATA_DIR/$GRADIENT  -fx 'v.p{g*v.w,0}' \)  +matte +swap \
    -compose CopyOpacity -composite  $WORK_DIR/pics/$f/title_txt.png

    if [ $FRAME_STYLE = "none" ]; then
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "Running: convert -size $INTRO_SIZE \
        $WORK_DIR/pics/$f/intro.png $WORK_DIR/pics/$f/title.png" >>$BVC_LOG.tmp
        cleanlog 1
        convert -size $INTRO_SIZE $WORK_DIR/pics/$f/intro.png \
        $WORK_DIR/pics/$f/title.png >> $BVC_LOG 2>&1
    else
        #  create a frame around our title picture
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "Running: $FRAME_CMD $WORK_DIR/pics/$f/intro.png \
        $INTRO_SIZE $WORK_DIR/pics/$f/title.png" >> $BVC_LOG.tmp
        cleanlog 1

        $FRAME_CMD $WORK_DIR/pics/$f/intro.png $INTRO_SIZE \
        $WORK_DIR/pics/$f/title.png
        if [ $FRAME_STYLE = "round" ]; then
            shadow $WORK_DIR/pics/$f/title.png
        fi


    #  paint the title and the title picture onto the black background
    convert   $WORK_DIR/pics/template.png $WORK_DIR/pics/$f/title_txt.png \
    -gravity south -geometry +0+65 -composite $WORK_DIR/pics/$f/title.png \
    -gravity north -composite  $WORK_DIR/pics/$f/background.png
     #  resize to proper size in case these operations alter the dimensions
     convert -resize $VID_SIZE_OPT! \
     $WORK_DIR/pics/$f/background.png $WORK_DIR/pics/$f/background.png
    fi
done

# end of title png loop

###############################################################################
#                      end of clip title image stuff                          #
###############################################################################

###############################################################################
#               create introductory video ("menu") if called for              #
###############################################################################

if [ $TITLE_PAGE = "none" ]; then
    :
else
    TITLE_PNGS=( "$(find $WORK_DIR -name intro.png)" )
#  create a transparant png with the title on it
    TITLE="My Video Collection"
    convert -font $FRAME_FONT -pointsize $TITLE_FONT_SIZE -size 420x \
    -gravity Center caption:"$TITLE"  -negate  \( +clone -blur 0x8 \
    -shade 110x45 -normalize \
    $DATA_DIR/$GRADIENT  -fx 'v.p{g*v.w,0}' \)  +matte +swap \
    -compose CopyOpacity -composite  $WORK_DIR/intro_txt.png

    # check if we are using static or animated images

    if [ $TITLE_PAGE = "plain" ]; then
        montage ${TITLE_PNGS[@]} -tile ${TILE_ARRAY[$FILES]} \
        -geometry ${GEO_ARRAY[$FILES]}+2+2 -background "#1E1E1E" -frame 3 \
        -bordercolor "#343634" miff:- |
        convert -size $VID_SIZE_OPT xc:"#1E1E1E" $WORK_DIR/intro_txt.png \
        -gravity south -geometry +0+55 -composite \
        - -gravity north -geometry +0+55 -composite \
        $WORK_DIR/title_page.png

        # create a fade-in and fade-out effect
        # copy enough pngs for the fade
        for ((i=0; i<=230; i++)); do
            cp $WORK_DIR/title_page.png $WORK_DIR/fade/title_page$i.png
        done

        # run the fade on the pngs
        # identify our target pngs
        for ((i=0; i<50; i++)); do
            FADIN_PNGS=( ${FADIN_PNGS[@]} $(find  $WORK_DIR/fade \
            -name title_page$i.png) )
        done

        for ((i=181; i<=230; i++)); do
            FADEOUT_PNGS=( ${FADEOUT_PNGS[@]} $(find $WORK_DIR/fade \
            -name title_page$i.png) )
        done
    # run the static_fade() function
        static_fade
        unset FADIN_PNGS FADEOUT_PNGS
        png2yuv  -f 29.970 -I p -b 1 -n 230 -j  $WORK_DIR/fade/title_page%0d.png |
        ffmpeg -f yuv4mpegpipe -i -  -an -vcodec mpeg4 -r 29.970 -b 1000 \
        -s $VID_SIZE_OPT -aspect 4:3 -y $INTRO_VIDEO 
        rm -f $WORK_DIR/fade/*.png

    elif [ $TITLE_PAGE = "animated" ]; then
        for (( count=0; count < $ANI_LENGTH; count++)); do
            ANI_PICS=$(find $WORK_DIR/pics/*[0-9]* -maxdepth 1 -name $count.png)

            montage ${ANI_PICS[@]} -tile ${TILE_ARRAY[$FILES]} \
            -geometry ${GEO_ARRAY[$FILES]}+2+2 -background "#1E1E1E" -frame 3 \
            -bordercolor "#343634" $WORK_DIR/montages/title_page$count.png
            # remove pngs
#            find $WORK_DIR/pics -name '[0-9]*.png'  -exec rm -f {} \;
        done

    # composite pics on $ANI_LENGTH grey templates numbered 1 to 300.png in animenu
        for ((PNGS=0; PNGS<$ANI_LENGTH; PNGS++)) ; do
            convert $WORK_DIR/pics/template.png \
            $WORK_DIR/intro_txt.png  -gravity south -geometry +0+60 -composite \
            $WORK_DIR/montages/title_page$PNGS.png -gravity north -geometry +0+60 -composite \
            $WORK_DIR/animenu/$PNGS.png
#            find $WORK_DIR/montages -name '*.png'  -exec rm -f {} \;
        done
        # convert pngs to video stream
        
        png2yuv  -f 29.970 -I p -b 3 -n $ANI_LENGTH -j  $WORK_DIR/animenu/%0d.png |
        ffmpeg -f yuv4mpegpipe -i -  -an -vcodec mpeg4 -r 29.970 -b 1000 \
        -s $VID_SIZE_OPT -aspect 4:3 -y $INTRO_VIDEO

    # create fade-in and fade-out for the animated menu
    LAST_ANI_PNG="$(( $ANI_LENGTH - 1 ))"
    for ((i=0; i<50; i++)); do
        cp $WORK_DIR/animenu/3.png $WORK_DIR/fade/intro_fade-in$i.png
        cp $WORK_DIR/animenu/$LAST_ANI_PNG.png $WORK_DIR/fade/intro_fadeout$i.png
        # remove animenu pngs to save space
#        find $WORK_DIR/animenu -name '*.png'  -exec rm -f {} \;
        FADIN_PNGS=( ${FADIN_PNGS[@]} $(find  $WORK_DIR/fade \
        -name intro_fade-in$i.png) )
        FADEOUT_PNGS=( ${FADEOUT_PNGS[@]} $(find $WORK_DIR/fade \
        -name intro_fadeout$i.png) )
    done
    echo -e "FADIN_PNGS are" "${FADIN_PNGS[@]}"
    echo -e "FADEOUT_PNGS are" "${FADEOUT_PNGS[@]}"
    sleep 10
    static_fade "intro page"
    INTRO_FADEIN="$WORK_DIR/intro_fade-in.avi"
    INTRO_FADEOUT="$WORK_DIR/intro_fadeout.avi"

    # make the fade-in video
    png2yuv  -f 29.970 -I p -b 1 -j  $WORK_DIR/fade/intro_fade-in%0d.png |
    ffmpeg -f yuv4mpegpipe -i -  -an -vcodec mpeg4 -r 29.970 -b 1000 \
    -s $VID_SIZE_OPT -aspect 4:3 -y $INTRO_FADEIN

    # make the fadeout video
    png2yuv  -f 29.970 -I p -b 1 -j  $WORK_DIR/fade/intro_fadeout%0d.png |
    ffmpeg -f yuv4mpegpipe -i -  -an -vcodec mpeg4 -r 29.970 -b 1000 \
    -s $VID_SIZE_OPT -aspect 4:3 -y $INTRO_FADEOUT
    unset FADIN_PNGS FADEOUT_PNGS
#    find $WORK_DIR/fade -name '*.png'  -exec rm -f {} \;

    fi
fi

# create silence for the intro
if [ $TITLE_PAGE = "none" ]; then
    :
else
    TIME=`vid_length "$INTRO_VIDEO"`
    cat /dev/zero | nice -n 0 sox -t raw -c 2 -r 48000 -w \
    -s - $WORK_DIR/intro.wav  trim 0 $TIME
    if [ $TITLE_PAGE = "plain" ]; then
   
        # convert to proper audio format
        ffmpeg -i $WORK_DIR/intro.wav \
        $AUDIO_OPTS -y $WORK_DIR/intro.$AUDIO_EXT

    elif [ $TITLE_PAGE = "animated" ]; then
        # create silence for fade-in and fadeout
        IFI_TIME=`vid_length "$INTRO_FADEIN"`
#        leave commented - might need this if adding background audio support
#        cat /dev/zero | nice -n 0 sox -t raw -c 2 -r 48000 -w \
#        -s - $WORK_DIR/intro_fadein.wav  trim 0 $IFI_TIME

        IFO_TIME=`vid_length "$INTRO_FADEOUT"`
#        cat /dev/zero | nice -n 0 sox -t raw -c 2 -r 48000 -w \
#        -s - $WORK_DIR/intro_fadeout.wav  trim 0 $IFO_TIME
        
        # make a ac3 of the proper length
        INTRO_TIME=$(echo "$TIME + $IFI_TIME + $IFO_TIME"|bc)
        ffmpeg -t $INTRO_TIME $AUDIO_OPTS \
        $WORK_DIR/intro.$AUDIO_EXT        

        echo -e "INTRO_TIME is $INTRO_TIME"
        sleep 5
        # convert to proper audio format
#        leave commented - might need this if adding background audio support
#        FF_FI_CMD=(ffmpeg -i $WORK_DIR/intro_fadein.wav \
#        $AUDIO_OPTS -y $WORK_DIR/intro_fadein.$AUDIO_EXT)
#        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
#        echo -e "Running ${FF_FI_CMD[@]}" >> $WORK_DIR/BVC.log.tmp
#        cleanlog 1
#        ${FF_FI_CMD[@]} >> $WORK_DIR/BVC.log.tmp 2>&1
#        cleanlog 3
#        FF_FO_CMD=(ffmpeg -i $WORK_DIR/intro_fadeout.wav \
#        $AUDIO_OPTS -y $WORK_DIR/intro_fadeout.$AUDIO_EXT)
#        echo -e "Running ${FF_FO_CMD[@]}" >> $WORK_DIR/BVC.log.tmp
#        cleanlog 1
#        ${FF_FO_CMD[@]} >> $WORK_DIR/BVC.log.tmp 2>&1
#        cleanlog 3
    fi
fi


###############################################################################
#                       work on the title lead-ins                            #
###############################################################################



# copy enough background.png's to destination for a lead-{in,out}
for ((i=0; i<=$FILES; i++)) ; do
        for ((a=0; a<=$TOTAL_PNGS; a++)) ; do
        cp $WORK_DIR/pics/$i/background.png $WORK_DIR/pics/$i/$a.png
    done
done


# finish the leadin operations, like identifying the target 
# pngs, dissolving, and making a video stream of them 

for ((i=0; i<=$FILES; i++)) ; do
    CLIP_CNT=$(($i + 1))
    # try to make the progress bar a little less irrelevent
    # percentage of total time taken for these operation (for progress bar)
    LEADIN_PCENT_TOTAL=30
    LEADIN_OPERATIONS=$(($V_ARRAY_TOTAL * 4))
    PROG_INC=$(echo "scale=0; $LEADIN_PCENT_TOTAL / $LEADIN_OPERATIONS"|bc -l)

    if [ $PROG_INC -lt 1 ]; then
    PROG_INC=1
    fi

    for ((PIC=0; PIC<50; PIC++)); do
        FADIN_PNGS=( ${FADIN_PNGS[@]} $(find  $WORK_DIR/pics/$i \
        -maxdepth 1 -name $PIC.png) )
    done

    for ((PIC=181; PIC<=230; PIC++)); do
        FADEOUT_PNGS=( ${FADEOUT_PNGS[@]} $(find $WORK_DIR/pics/$i \
        -maxdepth 1 -name $PIC.png) )
    done
    static_fade title
    unset FADIN_PNGS FADEOUT_PNGS

    # use png2yuv to convert to an mpeg stream
    PROGRESS_LABEL="converting title pngs of clip $CLIP_CNT to video"
    set_progress_bar_label
    png2yuv  -f 29.970 -I p -b 1 -n $TOTAL_PNGS -j  $WORK_DIR/pics/$i/%0d.png |
    ffmpeg -f yuv4mpegpipe -i -  -an -vcodec mpeg4 -r 29.970 -b 3000 \
    -s $VID_SIZE_OPT -aspect 4:3 -y "$WORK_DIR/pics/$i/$i-leadin.avi" 

    progress_bar_progress  $PROG_INC

    # remove pngs to save disk space
    find $WORK_DIR/pics/$i -name '[0-9]*.png'  -exec rm -f {} \;

    PROGRESS_LABEL="Creating silence for Titles" 
    set_progress_bar_label

    # create silence for leadin/leadout
    TIME=`vid_length $WORK_DIR/pics/$i/$i-leadin.avi`
    ffmpeg -t $TIME $AUDIO_OPTS \
    $WORK_DIR/pics/$i/$i-leadin.$AUDIO_EXT
    progress_bar_progress  $PROG_INC
done


###############################################################################
#                       end of title lead-in stuff                            #
###############################################################################


###############################################################################
#                       begin work on video fades                             #
###############################################################################

# create the pngs for the video fadeout from our new mpeg-4's 
#and move to proper fadeout dir
for ((i=0; i<=$FILES; i++)) ; do

    VID_LENGTH=`vid_length $WORK_DIR/pics/$i/$i.avi`
    ROUND_VID_LENGTH=`echo $VID_LENGTH|cut -f1 -d.`
    CUT_TIME=$[$ROUND_VID_LENGTH - 1]  # FIXME
    ffmpeg  -ss $CUT_TIME -i $WORK_DIR/pics/$i/$i.avi $WORK_DIR/%d.png

    VIDEO_FADEOUT_PNG=$(find $WORK_DIR -maxdepth 1 -name '[0-9]*.png'|tail -n 2|head -n 1)

    # just in case png creation failed, then use solid background
        if [ -z $VIDEO_FADEOUT_PNG ];then
            VIDEO_FADEOUT_PNG="$WORK_DIR/pics/template.png"
        fi

    cp $VIDEO_FADEOUT_PNG $WORK_DIR/pics/$i/video_fadeout.png 
    rm -f $WORK_DIR/[0-9]*.png
    # copy enough video_fadeout.png's to create a fade
    for ((a=0; a<=60; a++)) ; do
        cp $WORK_DIR/pics/$i/video_fadeout.png \
        $WORK_DIR/pics/$i/video_fadeout/$a.png
    done
done


# do the leadin operations on the video clip

for ((i=0; i<=$FILES; i++)) ; do
    CLIP_CNT=$(($i + 1))
    # try to make the progress bar a little less irrelevent
    # percentage of total time taken for these operation (for progress bar)

    FADEOUT_PCENT_TOTAL=20
    FADEOUT_OPERATIONS=$(($V_ARRAY_TOTAL * 3))
    PROG_INC=$(echo "scale=0; $FADEOUT_PCENT_TOTAL / $FADEOUT_OPERATIONS"|bc -l)
    if [ $PROG_INC -lt 1 ]; then
    PROG_INC=1
    fi

    S=40
    for ((Y=0; Y<=60; Y++)); do
        FADEOUT_PNGS=( ${FADEOUT_PNGS[@]} \
        $(find  $WORK_DIR/pics/$i/video_fadeout -name $Y.png) )

        # do the fadeout on each video
        PROGRESS_LABEL="processing $Y.png of $1 fade-out"
        set_progress_bar_label
        composite -dissolve $S $WORK_DIR/black.png \
        "${FADEOUT_PNGS[Y]}" "${FADEOUT_PNGS[Y]}"
        S=$((S+1))
    done
    unset FADEOUT_PNGS

    # update progress bar
    progress_bar_progress  $PROG_INC
    PROGRESS_LABEL="converting clip fadeout pngs of clip $CLIP_CNT to video"
    set_progress_bar_label

    # convert to video stream

    PNG2YUV_CMD="png2yuv  -f 29.970 -I p -b 1 -j \
    $WORK_DIR/pics/$i/video_fadeout/%0d.png"
    FFMPEG_CMD="ffmpeg -f yuv4mpegpipe -i - -an -vcodec mpeg4 -r 29.970 -s \
    $VID_SIZE_OPT -aspect 4:3 -b 3000 -y $WORK_DIR/pics/$i/$i-video_fadeout.avi"

    printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
    echo -e "\nRunning: $PNG2YUV_CMD | $FFMPEG_CMD\n" >> $BVC_LOG.tmp
    cleanlog 4

    SED_VAR="frame="
    if { $PNG2YUV_CMD | $FFMPEG_CMD ;}  >> $BVC_LOG.tmp 2>&1; then
        cleanlog 3
    else
        cleanlog 3
        OUTPUT="There was a problem converting the pngs to video. \
        Please see the output of $BVC_LOG"
        $KDIALOG --msgbox "$OUTPUT"
        dcop $dcopRef close
        exit 1
    fi

    # update progress bar
    progress_bar_progress  $PROG_INC
    PROGRESS_LABEL="creating silence for video fadeout of clip $CLIP_CNT"
    set_progress_bar_label

    # create silence for video fadeout
    TIME=`vid_length $WORK_DIR/pics/$i/$i-video_fadeout.avi`

    ffmpeg -t $TIME $AUDIO_OPTS \
    $WORK_DIR/pics/$i/$i-video_fadeout.$AUDIO_EXT

    # remove pngs to save space
#    rm -f $WORK_DIR/pics/$i/video_fadeout/*.png

    # update progress bar
    progress_bar_progress  $PROG_INC
done

###############################################################################
#                      end of video fade stuff                                #
###############################################################################


###############################################################################
#       join the files into one video and audio file, then mplex them         #
###############################################################################

PROGRESS_LABEL="Joining all video and audio, and combining into one file"
set_progress_bar_label

# put everything together into m2v and mp2,then mplex them together

for ((a=0; a<$V_ARRAY_TOTAL; a++)); do
    CLIP_AUDIOS=("${CLIP_AUDIOS[@]}" "$WORK_DIR/pics/$a/$a-leadin.$AUDIO_EXT" \
    "$WORK_DIR/pics/$a/$a.$AUDIO_EXT" \
    "$WORK_DIR/pics/$a/$a-video_fadeout.$AUDIO_EXT")
done

INTRO_FADEIN_AUDIO="$WORK_DIR/intro_fadein.$AUDIO_EXT"
INTRO_FADEOUT_AUDIO="$WORK_DIR/intro_fadeout.$AUDIO_EXT"
if [ ! $TITLE_PAGE = "animated" ]; then
    INTRO_FADEIN_AUDIO=""
    INTRO_FADEOUT_AUDIO=""
fi

JOINED_AUDIOS=("${JOINED_AUDIOS[@]}" "$WORK_DIR/intro.$AUDIO_EXT" \
"${CLIP_AUDIOS[@]}")

for ((i=0; i<$V_ARRAY_TOTAL; i++)); do
    CLIP_VIDEOS=("${CLIP_VIDEOS[@]}" "$WORK_DIR/pics/$i/$i-leadin.avi" \
    "$WORK_DIR/pics/$i/$i.avi" "$WORK_DIR/pics/$i/$i-video_fadeout.avi")
done
if [ ! $TITLE_PAGE = "animated" ]; then
    INTRO_FADEIN=""
    INTRO_FADEOUT=""
fi
JOINED_VIDEO=("${JOINED_VIDEO[@]}" "$INTRO_FADEIN" "$INTRO_VIDEO" "$INTRO_FADEOUT" "${CLIP_VIDEOS[@]}")

OUTPUT="clips from your videos"

# make sure the right number of files got created
#if test  `echo $JOINED_VIDEO | wc -w`  -ne $(($V_ARRAY_TOTAL * 3)) ; then
#    SORRY_MSG=$(sorry_msg)
#    $KDIALOG --msgbox "$SORRY_MSG"
#    dcop $dcopRef close
#    exit 1
#fi

OUTPUT="joined video"
COPY_CMD=(mencoder -quiet -oac copy -ovc copy ${JOINED_VIDEO[@]} \
-o $WORK_DIR/joined-tmp.avi)

printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
echo -e "\nRunning:" "${COPY_CMD[@]}" "\n"  >> $BVC_LOG.tmp
cleanlog 4

if "${COPY_CMD[@]}" >> $BVC_LOG.tmp 2>&1; then
    cleanlog 1
else
    cleanlog 1
    SORRY_MSG=$(sorry_msg)
    $KDIALOG --msgbox "$SORRY_MSG"
    dcop $dcopRef close
    exit 1
fi

progress_bar_progress 3
PROGRESS_LABEL="Converting our new video file to $TARGET mpeg-2 format"
set_progress_bar_label

OUTPUT="final joined svcd video"
JOIN_CMD=(ffmpeg -i $WORK_DIR/joined-tmp.avi -r 29.970 -f mpeg2video \
-tvstd ntsc $FFMPEG_OPTS -s $VID_SIZE_OPT -y $WORK_DIR/joined.m2v)

printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
echo -e "\nRunning ${JOIN_CMD[@]}\n"  >> $BVC_LOG.tmp
cleanlog 4

SED_VAR="frame="
if "${JOIN_CMD[@]}" >> $BVC_LOG.tmp 2>&1; then
    cleanlog 3
else
    cleanlog 3
    SORRY_MSG=$(sorry_msg)
    $KDIALOG --msgbox "$SORRY_MSG"
    dcop $dcopRef close
    exit 1
fi

# use cat to join the finished individual audio files
cat "${JOINED_AUDIOS[@]}" > $WORK_DIR/joined.$AUDIO_EXT

# update progress bar
progress_bar_progress 15
PROGRESS_LABEL="Joining the finished audio and video together"
set_progress_bar_label

OUTPUT="mplexed final video (audio plus video)"
MPLEX_CMD="mplex -V -f $MPLEX_FORMAT -b 230 -o $WORK_DIR/final.mpg \
$WORK_DIR/joined.m2v $WORK_DIR/joined.$AUDIO_EXT"

printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
echo -e "\nRunning: $MPLEX_CMD\n" >> $BVC_LOG.tmp
cleanlog 4

if $MPLEX_CMD >> $BVC_LOG.tmp 2>&1; then
    cleanlog 1
    echo "Exit code is $?" >> $BVC_LOG 
else
    cleanlog 1
    echo "Exit code is $?" >> $BVC_LOG 
    SORRY_MSG=$(sorry_msg)
    $KDIALOG --msgbox "$SORRY_MSG"
    dcop $dcopRef close
    exit 1
fi

###############################################################################
#                         begin burning stuff                                 #
###############################################################################

# set up some vars to make case statements easier
BVC_LOG="$WORK_DIR/BVC.log"

if [ $TARGET = "DVD" ]; then
    K3B_BURN_CMD="k3b --videodvd $WORK_DIR/FINAL/*"

elif [ $TARGET = "SVCD" ]; then
    K3B_BURN_CMD="k3b --cdimage $VCD_XML.cue"
fi

NOBURN_STRING="<html><H4>You selected to not burn right now<p> \
Your video files are  $WORK_DIR/FINAL/<p> \
You can burn later with: \
<p><font color='#0000C6' weight=900>"$K3B_BURN_CMD"</font><p> \
Thanks for using Ben's Video Converter !</html>"

if [ $TARGET = "DVD" ]; then
    $KDIALOG --yesno \
    "<html>Now we will preceed to burn<p> \
    Please insert a dvd+r or dvd+rw disk into your drive \
    and press 'Yes' when ready<p> \
    If for some reason you wish to cancel the burn press 'No' \
    and you can burn later</html>"

    case "$?" in
    # user goes ahead with the burn
    0 ) 
        PROGRESS_LABEL="Making dvd structure and configuration files"
        set_progress_bar_label

        OUTPUT="$WORK_DIR/FINAL/ directory structure for your DVD"
        DVDAUTHOR_CMD="dvdauthor  -x $DVD_AUTHOR_XML"
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "\nRunning: $DVDAUTHOR_CMD\n"  >> $BVC_LOG.tmp
        cleanlog 4

        if $DVDAUTHOR_CMD >> $BVC_LOG.tmp 2>&1; then
            SED_VAR="STAT:"
            cleanlog 3
        else
            cleanlog 2
            SORRY_MSG=$(sorry_msg)
            $KDIALOG --sorry "$SORRY_MSG"
            dcop $dcopRef close
            exit 1
        fi


        OUTPUT="DVD"
        # update progress bar
        progress_bar_progress 2
        PROGRESS_LABEL="Burning the dvd structure to DVD"
        set_progress_bar_label


:<<UNUSED
        DVD_BLANK_CMD="dvd+rw-format $BLANK $DEVICE"
        echo -e "Running: $DVD_BLANK_CMD\n" >> $BVC_LOG
        if $DVD_BLANK_CMD >> $BVC_LOG 2>&1; then
            :
        else
            $KDIALOG --msgbox \
            "<html>Oops, something went wrong, please check the media \
            you inserted is good and look at $BVC_LOG</html>"
            dcop $dcopRef close
            exit 1
        fi
UNUSED

        GROWISOFS_CMD="growisofs -use-the-force-luke=tty -dvd-compat \
        -Z /dev/dvd -dvd-video $WORK_DIR/FINAL/"
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "\nRunning: $GROWISOFS_CMD\n" |fold -bs|tr -s ' ' >> $BVC_LOG
        SORRY_MSG=$(sorry_msg)

        if $GROWISOFS_CMD >> $BVC_LOG.tmp 2>&1; then
            cleanlog 1
        else
            cleanlog 1
            $KDIALOG --msgbox "$SORRY_MSG"
            dcop $dcopRef close
            exit 1
        fi

        dcop $dcopRef setProgress 100
        ;;

    # user cancel out of the burn
    1 )
        dcop $dcopRef setProgress 100
        PROGRESS_LABEL="DONE !"
        set_progress_bar_label
        sleep 1
        # see if user wants to preview video
        $KDIALOG --yesno \
        "<html><h4>your converted and combined file is ready and can be \
        found at $WORK_DIR/final.mpg .  Do you wish to watch it now?</html>"


        # if yes, then play with mplayer
        if [ $? -eq 0 ]; then
            dcop $dcopRef close
            OUTPUT="$WORK_DIR/final.mpg"
            if test -f $OUTPUT; then
                mplayer $OUTPUT
                $KDIALOG --msgbox "$NOBURN_STRING"
                exit 0
            else
                SORRY_MSG=$(sorry_msg)
                $KDIALOG --sorry "$SORRY_MSG"
                dcop $dcopRef close
                exit 1
            fi
        else
            $KDIALOG --msgbox "$NOBURN_STRING"
            dcop $dcopRef close
            exit 0
        fi
        ;;
    esac

$KDIALOG $KDIALOG_OPTS --msgbox \
"<html><H3>Your burned disk should be ready<p> \
Thanks for using Ben's Video Converter !</html>"
cleanup
exit 0

elif [ $TARGET = "SVCD" ]; then

    # we are making a svcd
    PROGRESS_LABEL="Making svcd configuration, bin, and cue files"
    set_progress_bar_label
    printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
    VCDXGEN_CMD="vcdxgen -t svcd $WORK_DIR/final.mpg -o $VCD_XML"
        if $VCDXGEN_CMD >> $BVC_LOG.tmp 2>&1; then
            cleanlog 1
        else
            OUTPUT="svcd configuration file"
            SORRY_MSG=$(sorry_msg)
            $KDIALOG --sorry "$SORRY_MSG"
            dcop $dcopRef close
            exit 1
        fi

    OUTPUT="final SVCD bin and cue files for burning"
    VCDXBUILD_CMD="vcdxbuild -c "$VCD_XML.cue" -b "$VCD_XML.bin" "$VCD_XML""
    echo -e "\nRunning: "$VCDXBUILD_CMD"\n" >> $BVC_LOG.tmp
    cleanlog 4

    if $VCDXBUILD_CMD >> $BVC_LOG.tmp 2>&1; then
        cleanlog 1
    else
        cleanlog 1
        SORRY_MSG=$(sorry_msg)
        $KDIALOG --sorry "$SORRY_MSG"
        dcop $dcopRef close
        exit 1
    fi


    progress_bar_progress 10
    sleep 2

    # find out if we have a CDR or CDRW here, and blank if need be
    $KDIALOG --yesnocancel \
    "<html>Now we will preceed to burn<p> \
    Please insert a disk in your drive \
    <p>Is this a CDRW disk, or is it a ordinary CDR ? \
    <p>If it is a CDRW (rewritable disk) then press 'yes' \
    <p>If it is a CDR (write once disk) then press 'no'</html>"

    case "$?" in
    0 )

        PROGRESS_LABEL="Blanking the CD"
        set_progress_bar_label

        CDRW_BLANK_CMD="cdrdao blank --device $DEVICE"
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "\nRunning: $CDRW_BLANK_CMD\n" |fold -bs |tr -s ' ' >> $BVC_LOG

        if $CDRW_BLANK_CMD >> $BVC_LOG.tmp 2>&1; then
            cleanlog 1
            progress_bar_progress 5
        else
            cleanlog 1
            $KDIALOG $KDIALOG_OPTS --sorry \
            "<html><h4>There was a problem blanking the CD<p> \
            Please check $BVC_LOG</html>"
            dcop $dcopRef close
            exit 1
        fi

        PROGRESS_LABEL="Writing the CD"
        set_progress_bar_label

        CDRDAO_CMD="cdrdao write --device $DEVICE --driver generic-mmc \
        "$VCD_XML.cue""
        OUTPUT="SVCD disk"
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "\nRunning: $CDRDAO_CMD\n" >> $BVC_LOG.tmp
        cleanlog 4

        SED_VAR="Wrote"
        if $CDRDAO_CMD >> $BVC_LOG.tmp 2>&1; then
            cleanlog 3
            rm -f $BVC_LOG.tmp
        else
            cleanlog 3
            SORRY_MSG=$(sorry_msg)
            $KDIALOG --sorry "$SORRY_MSG"
            dcop $dcopRef close
            exit 1
        fi

        PROGRESS_LABEL="DONE !"
        set_progress_bar_label
        dcop $dcopRef setProgress 100
        ;;
    1 ) 
        PROGRESS_LABEL="Writing the CD"
        set_progress_bar_label
        sleep 2

        CDRDAO_CMD="cdrdao write --device $DEVICE --driver generic-mmc \
        "$VCD_XML.cue""

        SED_VAR="Wrote"
        printf "%s\n\n" "$LINE" "$LINE" >> $BVC_LOG
        echo -e "\nRunning: "$CDRDAO_CMD\n"" >> $BVC_LOG.tmp
        cleanlog 4
        if $CDRDAO_CMD >> $BVC_LOG.tmp 2>&1; then
            cleanlog 3
        else
            cleanlog 1
            OUTPUT="SVCD disk"
            SORRY_MSG=$(sorry_msg)
            $KDIALOG --sorry "$SORRY_MSG"
            dcop $dcopRef close
            exit 1
        fi

        sleep 2
        PROGRESS_LABEL="DONE !"
        set_progress_bar_label
        dcop $dcopRef setProgress 100
        sleep 2
        dcop $dcopRef close
        ;;
    2 )
        # user cancels
        OUTPUT="$WORK_DIR/final.mpg"
        dcop $dcopRef setProgress 100
        $KDIALOG --yesno \
        "<html><h4>your converted and combined file is ready and can be found \
        at $WORK_DIR/final.mpg .  Do you wish to watch it now?</html>"


        # if no, then exit with message
        # if yes, then play with mplayer
        if [ $? -ne 0 ]; then
            $KDIALOG --msgbox "$NOBURN_STRING"
            dcop $dcopRef close
            exit 0
        else
            dcop $dcopRef close
            if test -f $OUTPUT; then
                mplayer $OUTPUT
                $KDIALOG --msgbox "$NOBURN_STRING"
                exit 0
            else 
                SORRY_MSG=$(sorry_msg)
                $KDIALOG --sorry "$SORRY_MSG"
                dcop $dcopRef close
                exit 1
            fi
        fi
        ;;
    esac

fi

$KDIALOG $KDIALOG_OPTS $WIN_TITLE --msgbox \
"<html><H3>Your burned $TARGET disk should be ready<p> \
Thanks for using Ben's Video Converter !</html>"
cleanup
exit 0
